<template>
  <div>
    <el-card>
      <ul class="list-style-none friend-link-ul" v-if="friendLinkList.length">
        <li v-for="link of friendLinkList" :key="link.id">
          <a class="link-style-none" :href="link.url" target="_blank">
            <el-card class="friend-link-card m-2" shadow="hover">
              <el-image :src="link.favicon" />
              <h3 class="ml-1">{{link.title}}</h3>
            </el-card>
          </a>
        </li>
      </ul>
      <h3 v-else class="color-text-sub mb-3">你会是我的第一个朋友吗?</h3>
      <el-button :icon="plusIcon" v-on:click="addDialogVisible = true">申请友链</el-button>
    </el-card>
    <el-dialog title="友链申请" v-model="addDialogVisible" v-on:close="addDialogVisible = false" show-close>
      <friend-link-form v-model="friendLink" ref="addForm" />
      <p class="color-text-danger">注:申请后请及时将本站加入贵站友链哦～</p>
      <div class="clearfix">
        <el-button class="float-right" type="primary" v-on:click="applyFriendLink" v-loading="friendLinkApplying">申请</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {Options, Vue} from "vue-class-component";
import FriendLink from "@/domain/FriendLink";
import FriendLinkService from "@/service/FriendLinkService";
import {Plus} from "@element-plus/icons-vue";
import FriendLinkForm from "@/components/friend-link/FriendLinkForm.vue";
import {ElMessage} from "element-plus";

@Options({
  name: "FriendLinkView",
  components: {FriendLinkForm},
})
export default class FriendLinkView extends Vue{
  friendLinkList: FriendLink[]
  plusIcon = Plus
  addDialogVisible: boolean
  friendLinkApplying: boolean
  friendLink: FriendLink

  data(): any{
    return {
      friendLinkList: [],
      addDialogVisible: false,
      friendLinkApplying: false,
      friendLink: null
    }
  }

  async mounted(): Promise<void>{
    this.friendLinkList = await FriendLinkService.getAllList();
  }

  openLink(link: FriendLink): void{
    window.open(link.url)
  }

  async applyFriendLink(): Promise<void>{
    const result = await (this.$refs.addForm as FriendLinkForm).validate();
    if(result !== true) return;
    this.friendLinkApplying = true;
    try{
      await FriendLinkService.add(this.friendLink);
      this.friendLink = null;
      this.addDialogVisible = false;
      ElMessage.success("申请成功！博主会很快进行审核～")
    }finally {
      this.friendLinkApplying = false;
    }
  }
}
</script>

<style lang="scss">
.friend-link-ul{
  display: flex;
  flex-flow: row wrap;
  justify-content: center;
}
.friend-link-card>.el-card__body{
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: .5em 1em;
  img{
    height: 64px;
  }
}
</style>
